package controller

import (
	"errors"
	"gitee.com/fierce_wolf/go-fox-edge-common/commEnv"
	"gitee.com/fierce_wolf/go-fox-edge-common/commRedisService"
	"gitee.com/fierce_wolf/go-fox-edge-common/edgeEntity"
	"github.com/gin-gonic/gin"
	"go-fox-edge-kernel-gateway/token"
	"golang.org/x/crypto/bcrypt"
)

type authController struct {
}

func (e *authController) Login(context *gin.Context) (map[string]any, error) {
	username := context.Query("username")
	password := context.Query("password")

	userEntity := edgeEntity.Type.UserEntity.Instance()
	userEntity.UserName = username
	userEntity.PassWord = password

	// 检查：该用户是否存在
	exist, err := commRedisService.GetEntityByServiceKey(edgeEntity.Type.UserEntity.Type(), userEntity.MakeServiceKey())
	if err != nil {
		return nil, err
	}
	if exist == nil {
		return nil, errors.New("指定的用户不存在")
	}
	if password == "" {
		return nil, errors.New("密码不能为空")
	}

	// 验证：密码是否正确
	existEntity := exist.(*edgeEntity.UserEntity)
	err = bcrypt.CompareHashAndPassword([]byte(existEntity.PassWord), []byte(password))
	if err != nil {
		return nil, errors.New("密码验证不通过")
	}

	token, err := token.CreateToken(existEntity)
	if err != nil {
		return nil, err
	}

	data := gin.H{
		"tokenType":   "token",
		"accessToken": token,
	}

	return data, nil
}

func (e *authController) GetUserInfo(context *gin.Context) (map[string]any, error) {
	username := context.Query("username")

	// 检查：该用户是否存在
	userEntity := edgeEntity.Type.UserEntity.Instance()
	userEntity.UserName = username
	existUserEntity, err := commRedisService.GetEntityByServiceKey(edgeEntity.Type.UserEntity.Type(), userEntity.MakeServiceKey())
	if err != nil {
		return nil, err
	}
	if existUserEntity == nil {
		return nil, errors.New("指定的用户不存在")
	}

	// 检查：该用户是否存在
	userRole := edgeEntity.Type.UserRoleEntity.Instance()
	userRole.Name = (existUserEntity.(*edgeEntity.UserEntity)).Role
	existRoleEntity, err := commRedisService.GetEntityByServiceKey(edgeEntity.Type.UserRoleEntity.Type(), userRole.MakeServiceKey())
	if err != nil {
		return nil, err
	}
	if existRoleEntity == nil {
		return nil, errors.New("指定的用户不存在")
	}

	// 检查：该用户是否存在
	userPerm := edgeEntity.Type.UserPermissionEntity.Instance()
	userPerm.Name = (existUserEntity.(*edgeEntity.UserEntity)).Permission
	existUserPerm, err := commRedisService.GetEntityByServiceKey(edgeEntity.Type.UserPermissionEntity.Type(), userPerm.MakeServiceKey())
	if err != nil {
		return nil, err
	}
	if existUserPerm == nil {
		return nil, errors.New("指定的用户不存在")
	}

	data := gin.H{
		"nickname": username,
		"roles":    (existRoleEntity.(*edgeEntity.UserRoleEntity)).Params,
		"perms":    (existUserPerm.(*edgeEntity.UserPermissionEntity)).Params,
	}

	return data, nil
}

func (e *authController) GetUserMenu(context *gin.Context) (map[string]any, error) {
	username := context.Query("username")

	// 检查：该用户是否存在
	userEntity := edgeEntity.Type.UserEntity.Instance()
	userEntity.UserName = username
	existUserEntity, err := commRedisService.GetEntityByServiceKey(edgeEntity.Type.UserEntity.Type(), userEntity.MakeServiceKey())
	if err != nil {
		return nil, err
	}
	if existUserEntity == nil {
		return nil, errors.New("指定的用户不存在")
	}

	envType, ok := commEnv.GetArg("envType")
	if !ok {
		return nil, errors.New("envType参数不存在")
	}

	menuName := (existUserEntity.(*edgeEntity.UserEntity)).Menu
	if "docker" == envType {
		menuName = menuName + "-DOCKER"
	}

	// 检查：该用户是否存在
	userMenu := edgeEntity.Type.UserMenuEntity.Instance()
	userMenu.Name = menuName
	existMenuEntity, err := commRedisService.GetEntityByServiceKey(edgeEntity.Type.UserMenuEntity.Type(), userMenu.MakeServiceKey())
	if err != nil {
		return nil, err
	}
	if existMenuEntity == nil {
		return nil, errors.New("指定的用户不存在")
	}

	menus := (existMenuEntity.(*edgeEntity.UserMenuEntity)).Params

	data := gin.H{
		"menus": menus,
	}

	return data, nil
}

func (e *authController) TokenInfo(context *gin.Context) (map[string]any, error) {
	tokenStr := context.GetHeader("Authorization")
	tkn, clm, err := token.ParseToken(tokenStr)
	if err != nil {
		return nil, err
	}
	if !tkn.Valid || clm.Valid() != nil {
		return nil, errors.New("无效的token")
	}

	data := gin.H{
		"tokenName":           clm.Subject,
		"tokenValue":          tokenStr,
		"isLogin":             true,
		"loginId":             "admin",
		"loginType":           "login",
		"tokenTimeout":        3600 * 24 * 30,
		"sessionTimeout":      3600 * 24 * 30,
		"tokenSessionTimeout": -2,
		"tokenActiveTimeout":  -1,
		"loginDevice":         "default-device",
		"tag":                 nil,
	}

	return data, nil
}

func (e *authController) Logout(context *gin.Context) (map[string]any, error) {
	tokenStr := context.GetHeader("Authorization")
	tkn, clm, err := token.ParseToken(tokenStr)
	if err != nil {
		return nil, err
	}
	if !tkn.Valid || clm.Valid() != nil {
		return nil, errors.New("无效的token")
	}

	return nil, nil
}
